import request from "../../../utils/request";
import PubSub from 'pubsub-js';

Page({
    data: {
        date: '',
        recommendList: []
    },

    onLoad: function (options) {
        this.initDate();
        //订阅player页面发布过来的消息
        this.token = PubSub.subscribe('music', this.handleSubscribe);
    },

    onShow() {
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo) {
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                success: () => {
                    const page = '/pages/login/login';
                    const curPage = '/songPackage/pages/recommend/recommend';
                    wx.navigateTo({url: `${page}?source=${curPage}&isTab=false`});
                }
            });
            return;
        }
        this.getMusicList();
    },

    initDate() {
        const d = new Date();
        const month = d.getMonth() + 1;
        const day = d.getDate();
        this.setData({date: `${day} / ${month}`});
    },

    async getMusicList() {
        const res = await request('/recommend/songs');
        const recommendList = res.recommend || [];
        //歌手可能不止一个，需要拼接一下
        recommendList.forEach(item => {
            item.songer = item.artists.map(v => v.name).join('&');
        });
        this.setData({recommendList});
    },

    handlePlay(e) {
        const {id} = e.currentTarget.dataset;
        wx.navigateTo({url: '/songPackage/pages/player/player?songID=' + id});
    },

    handleSubscribe(msg, data) {
        const {recommendList} = this.data;
        const {type, songID} = data;
        let index = recommendList.findIndex(item => item.id === songID);
        if (type === 'next') {
            index = index === recommendList.length - 1 ? 0 : (index + 1);
        } else if (type === 'previous') {
            index = index === 0 ? (recommendList.length - 1) : (index - 1);
        }
        PubSub.publish('musicId', {songID: recommendList[index].id});
    },

    onUnload() {
        if (this.token) {
            PubSub.unsubscribe(this.token);
        }
    }
});
